(ns ura.select
  (:require
   [reagent.core :as r]
   [reagent.dom :as rd]
   [stylefy.core :as sty]
   [stylefy.reagent :as stylefy-reagent]
   [ajax.core :refer [GET POST DELETE]]
   [ura.common :as uc :refer [log spy]]
   [ura.style :as style :refer [attr]]
   [ura.popup :refer [showPopup]]

   ))

(defn my-option [& args]
  (let [
        [attrs & children]  args
        label (:label attrs)
        value (:value attrs)
        key   (:key   attrs)
        model (:model attrs)
        isChecked (r/atom (contains? @model value))
        toggleFn (fn []
                   (reset! isChecked (not @isChecked))
                   (if @isChecked
                     (swap! model conj value)
                     (swap! model disj value)
                     )
                   )
        ]
    (fn [& args]
      [:div (attr :flex)
       [:input (attr :.pointer :align-self=center :padding=5px
                   [:hover:bg "rgba(122, 122, 255, 0.5)"]
                   {:type "checkbox"
                    :checked @isChecked
                    :onChange toggleFn})]
       
       (into [:div (attr :w=100% [:padding "5px 0 5px 15px"] 
                  [:hover:bg "rgba(122, 122, 255, 0.5)"]
                  {:on-click toggleFn}
                  )
              ]
             children)
       ])))

(defn selectBox1 [opts model]
  (log "draw select box: " opts @model)
  (let [optlist (map (fn [opt]
                       (let [ [_ optAttr & optChild] opt]
                         (into [my-option (into optAttr {:model model})] optChild)
                         ))
                     opts)
        optDiv (into [:div ;; option list box
                      (attr
                       :min-w=200
                       :flex
                       :flex-col
                       :gap=10px
                       :m=10px
                       )
                      ]
                     optlist
                     )
        ]
  [:button (attr {:on-click #(showPopup % optDiv)} )

   [:i.fas.fa-arrow-drop-down]
   ]
  ))     


(defn my-select [& args]
  (let [
        [attrs & children]  args
        model (:model attrs)
        _ (reset! model (set @model))
        multiple? false
        ]
    [:div (attr
           :min-w=200
           :rounded=6
           :h=32
           :py=0
           :px=6
           :bgc=primary
           :display=flex
           :jc-b
           :outline=0.1px:solid:#8888ff
           )

     ;; selected item list
      (into [:div (attr :flex :gap=4px :align-items=center)]
            (map (fn [v] [:span.tag (attr :.small) v]) @model)
            )
      
      [selectBox1 children model]
      ]
    )
  )
